package com.heatup.apt.management.service.impl;

import com.heatup.apt.management.service.custom.*;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.common.dao.user.UserProductServiceMapper;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.model.coupon.CouponDetail;
import com.heatup.apt.model.coupon.CouponInfo;
import com.heatup.apt.model.management.Custom;
import com.heatup.apt.model.management.SysUser;
import com.heatup.apt.model.order.VipPurchaseLog;
import com.heatup.apt.model.product.ProductService;
import com.heatup.apt.model.user.UserBlacklist;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.user.UserProductService;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import java.util.*;

@Service
public class CustomServiceImpl implements CustomService {

    @Autowired
    private CustomMapper customMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VipPurchaseLogMapper vipPurchaseLogMapper;

    @Autowired
    private CouponInfoMapper couponInfoMapper;

    @Autowired
    private ProductServiceMapper productServiceMapper;
    @Autowired
    private UserProductServiceMapper userProductServiceMapper;
    
    @Autowired
    private UserBlacklistMapper userBlacklistMapper;

    private static final Logger logger = LoggerFactory.getLogger(CustomServiceImpl.class);


    /*
     * 获取客户列表
	 */
    @Override
    public Map<Object, Object> queryCustomList(int pageIndex, int pageSize, String mobile, int customLevel, String nickName, Integer id) {
        Map<Object, Object> resultMap = new HashMap<Object, Object>();

        Map<Object, Object> params = new HashMap<Object, Object>();
        params.put("pageNo", pageIndex * pageSize);
        params.put("pageSize", pageSize);
        params.put("mobile", mobile);
        params.put("customLevel", customLevel);
        params.put("nickName", nickName);
        params.put("id", id);
        List<Custom> user_list = customMapper.queryCustomList(params);
        resultMap.put("custom_list", user_list);

        final int user_count = customMapper.queryCustomCount(params);
        resultMap.put("custom_count", user_count);

        return resultMap;
    }

    //增加用户的vip天数，从当天开始算起
    public boolean addUserVipDayNum(int userId, int dayNum, int couponDetailId) {
        if (dayNum < 1) {
            logger.warn("warn: failed to add UserVipDay Count, userId:" + userId + ",dayNum:" + dayNum);
            return false;
        }
        UserInfo userInfo = userInfoMapper.selectById(userId);

        if (userInfo == null) {
            logger.warn("warn: failed not found this user: add UserVipDay Count, userId:" + userId + ",dayNum:" + dayNum);
            return false;
        }

        Date start_date = DateUtils.getDateShort(new Date());
        Date vipStartDate = DateUtils.getDateShort(new Date());
        Date end_date = null;
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, dayNum);// dayNum为增加的天数

        if (userInfo.getLevel() == 2) {  //本身就是vip用户
//			end_date = DateUtils.getDateShort(userInfo.getVipEndTime());
//			if (end_date.before(DateUtils.getDateShort(ca.getTime()))){   //如果加的天数，比用户原来的时间要大，（晚）
//				end_date = ca.getTime();
//			}
            end_date = DateUtils.getDateShort(userInfo.getVipEndTime()); //先取用户的vip结束时间
            vipStartDate = end_date;
            //原来是会员的，就一定是在原来的基础上增加天数
            end_date = DateUtils.AddDays(end_date, dayNum);  //加上该券的时间
        } else {
            end_date = DateUtils.getDateShort(ca.getTime());
            userInfo.setVipStartTime(start_date);
        }
        userInfo.setVipEndTime(end_date);
        userInfo.setUpdatedTime(start_date);
        userInfo.setLevel(2);
        int bool = userInfoMapper.updateSelectiveById(userInfo);

        logger.info("info: success to add UserVipDay Count, userId:" + userId + ",dayNum:" + dayNum);
        //modify by Earvin 2017-04-21 :写入日志信息
        try {
            VipPurchaseLog vipLog = new VipPurchaseLog();
            vipLog.setUserId(userId);
            vipLog.setOrderId(couponDetailId);
            vipLog.setPurchaseType(3);
            vipLog.setStartTime(vipStartDate);
            vipLog.setEndTime(end_date);
            vipLog.setCreatedTime(new Date());
            vipLog.setLevel(2);
            vipPurchaseLogMapper.insertSelective(vipLog);
        } catch (Exception e) {
            logger.error("更新檬会员兑换日志异常", e);
        }

        return true;
    }

    public ProductService addUserMonthTeamCourseProduct(int userId, int dayNum, CouponDetail couponDetail) {
        ProductService productService = null;
        Date vipStartDate =null;
        Date vipEndDate = null;
        CouponInfo couponInfo = couponInfoMapper.selectById(couponDetail.getCouponId());
        if(couponInfo !=null) {
             productService = productServiceMapper.queryMonthlyTeamCourseProductServiceByStoreId(Integer.valueOf(couponInfo.getLimitStore()));
            if(productService!=null){
                if (productService != null && dayNum > 0) {
                    UserProductService userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(userId, productService.getPServiceType());
                    if (userProductService != null) {
                        //如果存在该类型的优惠券，则需要在此基础上直接增加时间段。
                        //如果记录是有效的，则在endDate加上天数
                        if (userProductService.getIsvalid() == 1) {
                            vipStartDate= DateUtils.getDateShort(userProductService.getEndDate());
                            vipEndDate=DateUtils.AddDays(userProductService.getEndDate(), dayNum);
                            userProductService.setEndDate(vipEndDate);
                            userProductService.setUpdatedBy(userId);
                            userProductService.setUpdatedTime(new Date());
                            userProductService.setIsvaild(1);
                        } else {
                            vipStartDate = DateUtils.getDateShort(new Date());
                            vipEndDate = DateUtils.AddDays(vipStartDate, dayNum);
                            userProductService.setBeginDate(vipEndDate);
                            userProductService.setEndDate(DateUtils.AddDays(new Date(), dayNum));
                            userProductService.setUpdatedBy(userId);
                            userProductService.setUpdatedTime(new Date());
                            userProductService.setIsvaild(1);
                        }
                        userProductServiceMapper.updateById(userProductService);
                    } else {
                        //从未购买过该产品，则需要增加该产品的记录
                        userProductService = new UserProductService();
                        userProductService.setProductServiceType(productService.getPServiceType());
                        userProductService.setUserId(userId);
                        vipStartDate = DateUtils.getDateShort(new Date());
                        vipEndDate = DateUtils.AddDays(vipStartDate, dayNum);
                        userProductService.setIsvaild(1);
                        userProductService.setBeginDate(vipStartDate);
                        userProductService.setEndDate(vipEndDate);
                        userProductService.setCreatedBy(userId);
                        userProductService.setCreatedTime(new Date());
                        //插入到userProductService
                        userProductServiceMapper.insert(userProductService);
                    }

                    //插入日志表中
                    try {
                        VipPurchaseLog vipLog = new VipPurchaseLog();
                        vipLog.setUserId(userId);
                        vipLog.setOrderId(couponDetail.getId().intValue());
                        vipLog.setPurchaseType(4);
                        vipLog.setProductServiceId(productService.getId());
                        vipLog.setStartTime(vipStartDate);
                        vipLog.setEndTime(vipEndDate);
                        vipLog.setCreatedTime(new Date());
                        vipLog.setLevel(2);
                        vipPurchaseLogMapper.insertSelective(vipLog);
                    } catch (Exception e) {
                        logger.error("更新檬会员兑换日志异常", e);
                    }

                }
            }
        }

        return productService;
    }

	@Override
	public boolean userPullBlacklist(UserBlacklist userBlacklist, SysUser sysUser) {
		// TODO Auto-generated method stub
		userBlacklist.setCreateTime(new Date());
		userBlacklist.setCreateBy(String.valueOf(sysUser.getId()));
		int inserCount = userBlacklistMapper.insertSelective(userBlacklist);
		return inserCount > 0;
	}

}
